const express = require("express");
const router = express.Router();
const db = require("../mysql/index");

// 获取后台用户信息
router.post('/user/info',(req,res)=>{
  const sqlUrl='select * from houtai_user where userName = ? and userpass = ?'

  // 

  db.query(sqlUrl,[req.body.username,req.body.password],(err,ress)=>{

if(err) res.send({
  code: 404,
  message: "数据库查询用户信息失败",
})
console.log(ress);
if(ress.length!==0){
  // 生成token


  res.send({code:200,
  data:ress[0],
  message:'成功！'
})
}
  })
})

// 获取模组品牌

router.post("/obtainBrand",(req,res)=>{
// 获取总行数
let hang=0
const zong='SELECT COUNT(*) FROM brand where openid = ?;'
db.query(zong,req.user.id,(err,ress)=>{
  hang=ress?ress[0]['COUNT(*)']:0

    // const sqlurl = "select * from brand ORDER BY sort ASC";
    const sqlurlt = "select * from brand where status like ? and name like ? AND openid = ? ORDER BY sort ASC LIMIT ?,?";
    let nun=req.body

    let cha={}
   
   if(nun.input==''){
   cha.input="%"
   
   }else{
     cha.input=nun.input
   }
   if(nun.status==0){
     cha.status="%"
   }else{
     cha.status=nun.status
   }
   // 从哪里开始查询
   cha.currentPage=nun.pageSize*(nun.currentPage-1)
     db.query(sqlurlt,[cha.status,cha.input, req.user.id, cha.currentPage,nun.pageSize],(err,ress)=>{
   
       if(err) return res.send({
         code:404,
         message:'数据库请求失败'})
   
         if(ress.length!==0){
   
           res.send({
             code:200,
             data:ress,
             message:'获取模组品牌成功！',
             total:hang
           })
         }else if(ress.length==0){
           res.send({
             code:200,
             data:ress,
             total:hang,
             message:'获取模组品牌成功！'
           })
         }
     })
})


 }
 
 
)
// 添加模组品牌
router.post("/Addbrand",(req,res)=>{
 // 插入用户语句
//  插入前先判断是否已经有了相同的名称的
const yong = "select name from brand where name =?";

db.query(yong,req.body.name,(errs,rec)=>{
if(errs) return res.send({
  code:404,
  message:'数据库请求失败'})

// 已经存在品牌
if(rec.length!==0){
res.send({code:201,
  message:'该品牌已经存在！'})
// 不存在添加进去
}else{
 const id=Math.floor(Math.random()*1000000000)+1
 const charuUser = "insert into brand (id,name,status,sort,openid) values (?,?,?,?,?)";
  db.query(charuUser,[id,req.body.name,req.body.status,req.body.sort,req.user.id],(err,resb)=>{
  if(err) return res.send({
    code:404,
    message:'数据库请求失败'})

  if(resb.affectedRows==1){
    res.send({code:200,
      message:'模组品牌添加成功！'})
  }
  })
}
 
})


  
  })

// 删除模组品牌
  router.post('/deleteBrand',(req,res)=>{


    const deletepin='delete from brand where id=?'
    db.query(deletepin,req.body.id,(err,ress)=>{

      if(err) return res.send({
        code:404,
        message:'数据库删除品牌失败'})
        
        if(ress.affectedRows==1){
          res.send({
            code:200,
            message:'模组品牌删除成功！'})
        }

        
    })
  })
// 编辑模组品牌
router.post('/editBrand',(req,res)=>{
console.log(req.user.id);
let nun=req.body
const sqlurl = `update brand set name=?,status=?,sort=?,openid=? where id=?`;
db.query(sqlurl,[nun.name,nun.status,nun.sort,req.user.id,nun.id],(err,ress)=>{
if(err) return res.send({
  code:404,
  message:'数据库编辑模组品牌失败'})
if(ress.affectedRows==1){
  res.send({
    code:200,
    message:'编辑成功!'
  })
}
})
})
// 批量删除模组品牌
router.post('/batchDeleteBrand',(req,res)=>{
const sqlurl="DELETE  FROM brand where id=?"

  let nun=req.body.nunId
  let num=0
  nun.forEach((item)=>{
    db.query(sqlurl,item,(err,ress)=>{
   
      if(err) return res.send({
        code:404,
        message:'数据库编辑模组品牌失败'})
        if(ress.affectedRows==1){
          num++
        
    if(num==nun.length){
res.send({code:200,
  message:'批量删除成功!'})
    }
        }
    })

  })
})

// 添加模组型号
router.post('/addModuleModel',(req,res)=>{
  
 // 插入用户语句
//  插入前先判断是否已经有了相同的名称的
const yong = "select model from brand_model where model =? AND openid= ?";

db.query(yong,[req.body.model,req.user.id],(errs,rec)=>{
if(errs) return res.send({
  code:404,
  message:'数据库请求失败'})

// 已经存在品牌
if(rec.length!==0){
res.send({code:201,
  message:'该型号已经存在！'})
// 不存在添加进去
}else{

  let nun=req.body
 const id=Math.floor(Math.random()*1000000000)+1
 const charuUser = "insert into brand_model (id,model,lengths,height,Long_p,Wide_p,pitch,price,Communication_B,brand_id,openid) values (?,?,?,?,?,?,?,?,?,?,?)";
  db.query(charuUser,[id,nun.model,nun.lengths,nun.height,nun.Long_p,nun.Wide_p,nun.pitch,nun.price,nun.Communication_B,nun.brand_id,req.user.id],(err,resb)=>{
  if(err) return res.send({
    code:404,
    message:'数据库请求失败'})

  if(resb.affectedRows==1){
    res.send({code:200,
      message:'模组品牌添加成功！'})
  }
  })
}
 
})


}
  )
// 获取模组型号

router.post('/obtainModuleModel',(req,res)=>{



  // 获取总行数
let hang=0
const zong='SELECT COUNT(*) FROM brand_model where openid = ?;'
db.query(zong,req.user.id,(err,ress)=>{
  hang=ress?ress[0]['COUNT(*)']:0

    // const sqlurl = "select * from brand ORDER BY sort ASC";
    const sqlurlt = "select * from brand_model where brand_id like ? and model like ? AND openid= ?  LIMIT ?,?";
    let nun=req.body
  
    let cha={}
   
   if(nun.input==''){
   cha.input="%"
   
   }else{
     cha.input=nun.input
   }
   if(nun.status==0){
     cha.status="%"
   }else{
     cha.status=nun.status
   }
   
 
   // 从哪里开始查询
   cha.currentPage=nun.pageSize*(nun.currentPage-1)
   
     db.query(sqlurlt,[cha.status,cha.input,req.user.id,cha.currentPage,nun.pageSize],(err,ress)=>{
   
       if(err) return res.send({
         code:404,
         message:'数据库sdds请求失败'})
   
         if(ress.length!==0){
   
           res.send({
             code:200,
             data:ress,
             message:'获取模组品牌成功！',
             total:hang
           })
         }else if(ress.length==0){
           res.send({
             code:200,
             data:ress,
             total:hang,
             message:'获取模组品牌成功！'
           })
         }
     })
})

})
// 编辑模组型号
router.post('/editModuleModel',(req,res)=>{


  let nun=req.body
const sqlurl = `update brand_model set model=?,lengths=?,height=?,Long_p=?,Wide_p=?,pitch=?,price=?,Communication_B=?,brand_id=? where id=?`;
db.query(sqlurl,[nun.model,nun.lengths,nun.height,nun.Long_p,nun.Wide_p,nun.pitch,nun.price,nun.Communication_B,nun.brand_id,nun.id],(err,ress)=>{
if(err) return res.send({
  code:404,
  message:'数据库编辑模组品牌失败'})
if(ress.affectedRows==1){
  res.send({
    code:200,
    message:'编辑成功!'
  })
}
})
})

// 删除模组型号
router.post('/deleteModuleModel',(req,res)=>{

  
  const deletepin='delete from brand_model where id=?'
  db.query(deletepin,req.body.id,(err,ress)=>{

    if(err) return res.send({
      code:404,
      message:'数据库删除模组型号失败'})
      
      if(ress.affectedRows==1){
        res.send({
          code:200,
          message:'模组品牌删除成功！'})
      }

      
  })

})
// 批量删除模组型号
router.post('/batchDeleteModuleModel',(req,res)=>{
  console.log(req.body);

  const sqlurl="DELETE  FROM brand_model where id=?"

  let nun=req.body.nunId
  let num=0
  nun.forEach((item)=>{
    db.query(sqlurl,item,(err,ress)=>{
   
      if(err) return res.send({
        code:404,
        message:'数据库编辑模组品牌失败'})
        if(ress.affectedRows==1){
          num++
        
    if(num==nun.length){
res.send({code:200,
  message:'批量删除成功!'})
    }
        }
    })

  })
})









// 获取用户信息
router.post("/information", (req, res) => {


  const arr = req.user;
  const sqlurl = "select * from users where id =?";

  db.query(sqlurl, arr.id, (err, ress) => {

    // 用户最近聊天不要返回
    delete ress[0].recentChats;
    // 用户密码不要返回
    delete ress[0].passWord;
    // 用户的好友列表不返回
    delete ress[0].friend
    // 返回用户信息
    if (ress.length !== 0) {
      res.send({
        code: 200,
        data: ress[0],
        status: "获取用户信息成功",
      });
    } else {
      res.send({
        code: 201,
        status: "获取失败",
      });
    }
  });
});
// 修改头像

router.post("/Modify", (req, res) => {
  const arr = req.user;

  const sqlurl = `update users set userHead=? where id=?`;

  db.query(sqlurl, [req.body.img, arr.id], (err, resa) => {
    if (resa.affectedRows === 1) {
      res.send({
        code: 200,
        data: req.body,
        status: "头像修改成功！",
      });
    }
  });
});

// 修改个人信息
router.post("/modifyInformation", (req, res) => {

  const arr = req.body;

  // 先判断是否有重名用户
  const yong = "select * from users where userName =?";

  db.query(yong, arr.userName, (errs, rescc) => {
  
    // 证明有相同的用户
    if (rescc.length == 1) {
      res.send({code: 201, status: "用户名已经存在"});
    } else {
      const sqlurls = `update users set ? where id=?`;

      db.query(sqlurls, [arr, arr.id], (err, resa) => {
        if (resa.affectedRows === 1) {
          res.send({
            code: 200,
            status: "个人信息修改成功!",
          });
        }
      });
    }
  });
});
// 获取用户最近聊天人
router.post("/recentchats", (req, res) => {
  // 查询用户的信息
  const yong = "select recentChats from users where id =?";

  db.query(yong,req.user.id,(err,ress)=>{

 


if(!err){

  if(ress[0]){
    let aes=JSON.parse(ress[0].recentChats)

    res.send({code:200,
      data:aes,
  status:"最近聊天获取成功"})
  }else{res.send({
    code:201,
    status:"无最近聊天"})}
   
}
  })



});
// 获取好友列表
router.get("/chatFriends",(req,ress)=>{


  const das="select friend from users where id =? "
 

  db.query(das,req.query.id,(err,res)=>{
   if(!err){

 
if(res[0].friend){
  ress.send({code:200,
  data:JSON.parse(res[0].friend),
status:'好友获取成功！'})
}else{

  ress.send({code:201,data:null,status:'好友为空'})
}
   }
  })
})
// 创建获取聊天对象的接口
module.exports = router;
